package com.tanger.common.excel;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.IndexedColors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

/**
 * Excel工具类(无样式)
 */
public class ExcelUtils {

	private ExcelUtils() {

	}

	/**
	 * 导出Excel
	 * 
	 * @param headList  Excel表头列表
	 * @param dataList  Excel内容列表
	 * @param sheetName Excel工作表名称
	 * @param response  响应对象
	 * @throws IOException
	 */
	public static void exportExcel(List<String> headList, List<LinkedHashMap<String, Object>> dataList, String sheetName, HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		ServletOutputStream servletOutputStream = null;
		try {
			servletOutputStream = response.getOutputStream();
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			//String fileName = new String((sheetName+dateFormat.format(new Date())).getBytes(), StandardCharsets.UTF_8);
			String fileName = URLEncoder.encode(sheetName+dateFormat.format(new Date()), "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
			ExcelWriter writer = new ExcelWriter(servletOutputStream, ExcelTypeEnum.XLSX, true);
			Sheet sheet = new Sheet(1, 0);
			sheet.setSheetName(sheetName);
			sheet.setAutoWidth(Boolean.TRUE);//自适应列宽

			Table table = new Table(1);
			TableStyle style = new TableStyle();
			style.setTableHeadBackGroundColor(IndexedColors.PALE_BLUE);//浅蓝色：PALE_BLUE；CORNFLOWER_BLUE
			Font font = new Font();
			font.setFontHeightInPoints((short)10);
			style.setTableHeadFont(font);
			table.setTableStyle(style);
			List<List<String>> head = new ArrayList<>();
			if (!CollectionUtils.isEmpty(headList)) {
				headList.forEach(headName -> head.add(Arrays.asList(headName)));
			}
			table.setHead(head);
			Map<Integer, Integer> columnWidthMap = new HashMap<>();

			List<List<String>> data = new ArrayList<>();
			Integer index = 0;
			if (!CollectionUtils.isEmpty(dataList)) {
//				for (LinkedHashMap<String,Object> map : dataList){
//					List<String> list = new ArrayList<>();
//					for (Entry<String, Object> entry : map.entrySet()) {
//						Object value = entry.getValue();
//						Integer num = (value == null ? 0 : value.toString().length());
//						columnWidthMap.put(index,num);
//						index++;
//					}
//				}
				dataList.forEach(map -> {
					List<String> list = new ArrayList<>();
					for (Entry<String, Object> entry : map.entrySet()) {
						if (!entry.getKey().equals("elapsedTime")){
							Object value = entry.getValue();
							list.add(value == null ? "" : value.toString());
						}else {
							Object value = entry.getValue();
							list.add(value == null ? "" : value.toString()+"秒");
						}
					}
					data.add(list);
				});
			}
			//sheet.setColumnWidthMap(columnWidthMap);//设置列宽
			writer.write0(data, sheet, table);
			writer.finish();
			servletOutputStream.flush();
		} catch (IOException e) {
			throw new RuntimeException(e.toString());
		} finally {
			if (servletOutputStream != null) {
				servletOutputStream.close();
			}
		}
	}


	/**
     * @param   fileNames
     * @param   request
     * @Description: 导出文件转换文件名称编码
     */
    public static String encodeFileName(String fileNames, HttpServletRequest request) {
        String codedFilename = null;
        try {
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident") || null != agent && -1 != agent.indexOf("Edge")) {// ie浏览器及Edge浏览器
                String name = URLEncoder.encode(fileNames, "UTF-8");
                codedFilename = name;
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                // 火狐,Chrome等浏览器
                codedFilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return codedFilename;
    }
}
